package cn.kduck.assembler.security.authentication;

import cn.kduck.security.configuration.HttpSecurityConfigurer;
import cn.kduck.security.mfa.MfaAuthenticationProvider;
import cn.kduck.security.mfa.MfaAuthenticationValidationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
public class PhoneNumAuthenticationConfiguration implements HttpSecurityConfigurer {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private UserNameService userNameService;

    @Autowired(required = false)
    private MfaAuthenticationProvider mfaAuthenticationProvider;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(phoneNumAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    public PhoneNumAuthenticationFilter phoneNumAuthenticationFilter(){
        PhoneNumAuthenticationFilter phoneNumAuthenticationFilter = new PhoneNumAuthenticationFilter();

        List<AuthenticationProvider> providerList = new ArrayList<>(2);

        if(mfaAuthenticationProvider != null){
            providerList.add(mfaAuthenticationProvider);
        }

        PhoneNumAuthenticationProvider phoneNumAuthenticationProvider = new PhoneNumAuthenticationProvider(userNameService, userDetailsService);
        providerList.add(phoneNumAuthenticationProvider);

        ProviderManager providerManager = new ProviderManager(providerList);

        phoneNumAuthenticationFilter.setAuthenticationManager(providerManager);
//        phoneNumAuthenticationFilter.setAuthenticationManager(new PhoneNumAuthenticationManager(userNameService,userDetailsService));
        return phoneNumAuthenticationFilter;
    }

}
